package com.crack.spansframe;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;

import com.crack.spansframe.extra.IAsync;
import com.crack.spansframe.extra.ICache;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 可异步加载的ImageSpan
 * Created by liuyu on 16-4-20.
 */
public class AsyncImageSpan extends SpanImageSpan implements IAsync<Bitmap> {
    ICache mCache;

    public AsyncImageSpan(String source, SpannableStringBuilder spannableStringBuilder, ICache iCache) {
        super(source, spannableStringBuilder);
        mCache = iCache;
    }

    @Override
    public Bitmap get() {
        if (mCache.get(mSource) != null) {
            return null;
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(mSource).openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            return BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    @Override
    public void set(Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }
        Drawable drawable = new BitmapDrawable(mTextView.getResources(), bitmap);
        mCache.put(mSource, drawable);
        if (mTag != null && mTag.equals(mTextView.getTag())) {
            mTextView.setText(mSpan);
        }
    }

    @Override
    protected Drawable getCache(String source) {
        return mCache.get(source);
    }
}
